const fse = require('fs-extra');
const http = require('http');
const Controller = require('./src/controller');
const { PORT } = require('./src/config')
const controller = new Controller()
const server = http.createServer()

/**
 * 案例：
 * https://blog.csdn.net/qiwoo_weekly/article/details/124138526
 * https://juejin.cn/post/7071877982574346277
 */

// 监听请求事件
server.on("request", async (req, res) => {
    const { url, method } = req
    res.setHeader('Access-Control-Allow-Origin', "*");
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.setHeader("Content-Type", "application/json;");
    if (method === 'OPTIONS') {
        res.status = 200;
        return res.end();
    }

    switch (url) {
        case '/file/upload_chunks':
            await controller.uploadChunks(req, res);
            return
        case '/file/merge_chunks':
            await controller.mergeChunks(req, res);
            return
        case '/file/get_chunks':
            await controller.getChunks(req, res);
            return;
        case '/file/verify_chunk':
            await controller.verifyChunk(req, res);
            return;
        default:
            res.status = 404
            res.end('404')
            break
    }
});

// 启动服务
server.listen(PORT, () => {
    console.log(`应用已经启动，http://localhost:${PORT}`)
})
